package com.zzzzzz.account.settings;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import com.zzzzzz.account.user.UserDao;
import com.zzzzzz.common.util.ImageUtils;
import com.zzzzzz.core.data.filestore.FileData;
import com.zzzzzz.core.data.filestore.FileStorage;

@Service("profilePictureService")
public class FileStorageProfilePictureService implements ProfilePictureService {

	@Resource
	private FileStorage storage;
	@Resource
	private UserDao userDao;
	
	public void saveProfilePicture(Long userId, byte[] imageBytes) throws IOException {
		assertBytesLength(imageBytes);
		String contentType = guessContentType(imageBytes);
		assertContentType(contentType);
		storage.storeFile(new FileData("u/s/" + userId + ".jpg", ImageUtils.scaleImage(imageBytes, "jpeg", 170, 400), contentType));
		storage.storeFile(new FileData("u/n/" + userId + ".jpg", ImageUtils.scaleImage(imageBytes, "jpeg", 300, 500), contentType));
		storage.storeFile(new FileData("u/l/" + userId + ".jpg", ImageUtils.scaleImage(imageBytes, "jpeg", 1920, 3000), contentType));
		userDao.editPicSet(userId, true);
	}

	private void assertBytesLength(byte[] imageBytes) {
		int length = imageBytes.length;
		if (length == 0) {
			throw new IllegalArgumentException("Cannot accept empty picture byte[] as a profile picture");
		} else if(length > 3145728){
			throw new MaxUploadSizeExceededException(3145728);
		}
	}

	private String guessContentType(byte[] imageBytes) throws IOException {
		return URLConnection.guessContentTypeFromStream(new ByteArrayInputStream(imageBytes));
	}

	private void assertContentType(String contentType) {
		if (!IMAGE_TYPES.contains(contentType)) {
			throw new IllegalArgumentException("Cannot accept content type '" + contentType + "' as a profile picture.");
		}
	}

	private static final List<String> IMAGE_TYPES = Arrays.asList("image/jpeg", "image/gif", "image/png");
	
}